package com.fance.controller;

import com.fance.model.EntityType;
import com.fance.model.HostHolder;
import com.fance.model.News;
import com.fance.model.ViewObject;
import com.fance.service.LikeService;
import com.fance.service.NewsService;
import com.fance.service.UserService;
import com.fance.util.MailSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fance
 * @date 18-5-4 上午6:00
 */
@Controller
public class HomeController {

    @Autowired
    private UserService userService;

    @Autowired
    private NewsService newsService;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    LikeService likeService;

    @Autowired
    MailSender mailSender;


    private List<ViewObject> getNews(int userId, int offset, int limit) {
        List<News> newsList = newsService.getLatestNews(userId,offset,limit);
        int localUserId = hostHolder.getUser() != null ? hostHolder.getUser().getId() : 0;
        List<ViewObject> viewObjectList = new ArrayList<>();
        for (News news: newsList) {
            ViewObject viewObject = new ViewObject();
            viewObject.set("news", news);
            viewObject.set("user", userService.getUser(news.getUserId()));

            if (localUserId != 0) {
                viewObject.set("like", likeService.getLikeStatus(localUserId, EntityType.ENTITY_NEWS,news.getId()));
            } else {
                viewObject.set("like",0);
            }

            viewObjectList.add(viewObject);
        }
        return viewObjectList;
    }


    @RequestMapping(path = {"/", "/index"}, method = {RequestMethod.GET,RequestMethod.POST})
    public String index(Model model,
                        @RequestParam(value = "pop",defaultValue = "0") int pop) {
        model.addAttribute("vos", getNews(0,0,10));
        if (hostHolder.getUser() != null) {
            pop = 0;
        }
        model.addAttribute("pop",pop);
        return "home";
    }

    @RequestMapping(path = {"/user/{userId}/"}, method = {RequestMethod.GET,RequestMethod.POST})
    public String userIndex(Model model, @PathVariable("userId") int userId) {
        model.addAttribute("vos", getNews(userId,0,10));
        return "home";
    }


}
